package cn.sc.summer.core.aspect;

import cn.hutool.core.text.CharSequenceUtil;
import cn.sc.summer.core.annotation.LengthValid;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 类名：字符串长度校验逻辑
 *
 * @author a-xin
 * @date 2024/5/7 13:15
 */
@Slf4j
public class LengthValidAspect implements ConstraintValidator<LengthValid, String> {

    private int min;

    private int max;

    @Override
    public void initialize(LengthValid constraintAnnotation) {
        min = constraintAnnotation.min();
        max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (CharSequenceUtil.isBlank(value)) {
            return Boolean.TRUE;
        }
        int length = value.length();
        return length >= min && length <= max;
    }
}
